package com.hangyutech.strelitzia.exception;

import com.hangyutech.strelitzia.constant.HttpResultCodeEnum;
import com.hangyutech.strelitzia.vo.HttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public HttpResult bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return HttpResult.error().message(e.getErrorMsg());
//        e.getErrorCode()
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public HttpResult exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("发生空指针异常！原因是:", e);
//        return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
        return HttpResult.error().message(HttpResultCodeEnum.RECORD_NOT_FOUND.getMessage());
    }


    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public HttpResult exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("未知异常！原因是:", e);
        logger.error("未知异常！原因是:", e.getMessage());
//        return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
        return HttpResult.error()
                .message(e.getMessage());
//                .data(e.getStackTrace());
    }
}
